/* linkit.js
 * By François Leporcq
 * MIT Licensed.
 */
var Ellipse = AbstractShape.extend({
    _className: "Ellipse",
    init: function(origin, xRadius, yRadius){
        this._origin = origin;
        this._xRadius = xRadius;
        this._yRadius = yRadius;
    },
    getCenter: function(){
        return this.getOrigin();
    },
    setXRadius: function(xRadius){
        this._xRadius = xRadius;
    },
    getXRadius: function(){
        return this._xRadius;
    },
    setYRadius: function(yRadius){
        this._yRadius = yRadius;
    },
    getYRadius: function(){
        return this._yRadius;
    },
    getBox: function(){
        var width = 2 * this.getXRadius();
        var height = 2*this.getYRadius();
        var origin = new Point(this._origin.getX() - this.getXRadius(), this._origin.getY() - this.getYRadius());
        return new Rectangle(origin, width, height).getBox();
    },
    getInBox: function(){
        var width = this._xRadius * Math.sqrt(2);
        var height = this._yRadius * Math.sqrt(2);
        var origin = new Point(this._origin.getX() - width / 2, this._origin.getY() - height / 2);
        return new Rectangle(origin, width, height);
    },
    getAnchor: function(point){
        var deltaX = point.getX() - this._origin.getX(),
            deltaY = point.getY() - this._origin.getY();

        if (deltaX == 0 || deltaY == 0){
            return this.getBox().getAnchor(point);
        }

        var m = deltaY / deltaX,
            mSquared = m * m,
            xRadiusSquared = this.getXRadius() * this.getXRadius(),
            yRadiusSquared = this.getYRadius() * this.getYRadius(),
            x = Math.sqrt(1 / ((1 / xRadiusSquared) + (mSquared / yRadiusSquared)));

        if (deltaX < 0){
            x = -x;
        }

        var y = m * x;

        var anchorX = this._origin.getX() + x;
        var anchorY = this._origin.getY() + y;

        var inBox = this.getInBox();
        var cardinalPoint;
        if(anchorX >= inBox.getOrigin().getX() + inBox.getWidth()){
            cardinalPoint = ECardinalPoint.EAST;
        }else if(anchorX <= inBox.getOrigin().getX()){
            cardinalPoint = ECardinalPoint.WEST;
        }else if(anchorY >= inBox.getOrigin().getY() + inBox.getHeight()){
            cardinalPoint = ECardinalPoint.NORTH;
        }else if(anchorY <= inBox.getOrigin().getY()){
            cardinalPoint = ECardinalPoint.SOUTH;
        }

        return new Anchor(anchorX, anchorY, cardinalPoint);
    }
}).implement([Linkable]);